package com.amt.olcacon;

import com.amt.olcacon.db.DerbyConfig;
import org.openlca.core.DataDir;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.zeroturnaround.zip.ZipUtil;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.Arrays;
import java.util.Collections;
import java.util.Locale;
import java.util.stream.Collectors;

public class UnzipZOLCA {

    private static final Logger log = LoggerFactory.getLogger(UnzipZOLCA.class);

    /**
     * 主方法执行流程：
     * 1. 创建数据库存储目录
     * 2. 解压ZOLCA备份文件
     * 3. 配置MySQL连接参数
     * 4. 将配置保存到databases.json
     */
    public static void main(String[] args) {
        try {
            // 1. 创建数据库存储目录
            var dbFolder = DataDir.get().getDatabasesDir();
            Files.createDirectories(dbFolder.toPath());

            // 2. 解压ZOLCA备份文件
            File zolca = new File("H:\\ecoinvent数据库\\ecoinvent_391_consequential_lci.zolca");
            if (!zolca.exists()) {
                throw new IOException("ZOLCA文件不存在: " + zolca.getAbsolutePath());
            }

            var dbName = getDatabaseName(zolca, dbFolder);
            var folder = new File(dbFolder, dbName);
            Files.createDirectories(folder.toPath());
            ZipUtil.unpack(zolca, folder);
            log.info("成功解压ZOLCA文件到: {}", folder.getAbsolutePath());

            var db = DataDir.get().openDatabase(DerbyConfig.DBNAME);
            org.openlca.core.database.upgrades.Upgrades.on(db);


        } catch (IOException e) {
            log.error("导入ZOLCA文件失败", e);
            throw new RuntimeException("导入ZOLCA文件失败", e);
        }
    }


    /**
     * 生成不冲突的数据库名称
     *
     * @param zolca    备份文件
     * @param dbFolder 数据库目录
     * @return 可用的数据库名称(自动处理重名情况)
     */
    private static String getDatabaseName(File zolca, File dbFolder) {
        // 使用文件名作为基础名称(去掉.zolca后缀)
        var proposal = zolca.getName();
        if (proposal.toLowerCase(Locale.US).endsWith(".zolca")) {
            proposal = proposal.substring(0, proposal.length() - 6);
        }
        // 获取现有数据库名称集合(小写)
        var existing = dbFolder.list();
        var names = existing == null
                ? Collections.emptySet()
                : Arrays.stream(existing)
                .map(String::toLowerCase)
                .collect(Collectors.toSet());
        // 处理名称冲突，自动添加序号
        String name = proposal;
        int count = 0;
        while (names.contains(name.toLowerCase())) {
            count++;
            name = proposal + " (" + count + ")";
        }
        return name;
    }

}
